<template>
	<view class="pageview">
		<video :src="videoUrl" controls style="width: 750rpx;height: 100%;" autoplay show-center-play-btn
			play-btn-position='center' v-if="videoUrl">
			<cover-view style="position:absolute;left:15px;" :style="{top:statusBarHeight + 15 + 'px'}">
				<cover-image src="/static/fanhui.png" mode="" style="width: 40rpx;height: 40rpx;"
					@click="back()"></cover-image>
			</cover-view>
			<cover-view style="position:absolute;right:15px;" :style="{top:statusBarHeight + 10 + 'px'}"
				v-if="this.videoUrl">
				<cover-image src="/static/download.png" mode="" style="width: 60rpx;height: 60rpx;"
					@click="download(videoUrl)"></cover-image>
			</cover-view>
		</video>
	</view>
</template>

<script>
	import StorageCache from '@/common/mediacache/index.js';
	import mediaCache from '@/common/mediacache/mediaCache.js'; // 适配你的实际路径
	export default {
		data() {
			return {
				videokey: '',
				fileTpye: 'video',
				videoUrl: '',
				uploadType: 'chat',
				longPressTimer: null,
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight
			}
		},
		onLoad(e) {
			let systemInfo = uni.getSystemInfoSync();
			if (systemInfo.platform === 'android') {
				var Color = plus.android.importClass("android.graphics.Color");
				var activity = plus.android.runtimeMainActivity();
				activity.getWindow().setNavigationBarColor(Color.argb(255, 0, 0, 0));
			}
			let query = this.$Route.query
			this.videokey = query.video
			if (query.type) {
				this.uploadType = query.type
			}
			this.loadVideo()
		},
		onUnload() {
			let systemInfo = uni.getSystemInfoSync();
			if (systemInfo.platform === 'android') {
				var Color = plus.android.importClass("android.graphics.Color");
				plus.android.importClass("android.view.Window");
				var mainActivity = plus.android.runtimeMainActivity();
				mainActivity.getWindow().setNavigationBarColor(Color.argb(255, 12, 13, 26));
			}
		},
		methods: {
			isLocalPath(path) {
				// 使用正则表达式匹配以"/"、"file:/"或"_doc/"开头的路径
				return /^\/|^file:\/|^_doc\//i.test(path);
			},
			async loadVideo() {
				try {
					const cachedMedia = await mediaCache.loadMedia(this.videokey, this.uploadType, this.fileTpye);
					this.setVideoSource(cachedMedia);
				} catch (error) {
					console.log(error);
					this.handleLoadError(error);
				}
			},

			setVideoSource(src) {
				this.videoUrl = src
				console.log(this.videoUrl);
			},
			handleLoadError(error) {
				console.error('Video loading error:', error);
			},
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			download(videoUrl) {
				if (this.isLocalPath(videoUrl)) {
					this.saveVideo(videoUrl)
				} else {
					let localKey = `${this.fileTpye}_${this.uploadType}_cache_list`
					const cachedUrl = StorageCache.getCachedUrl(localKey, this.videokey);
					if(this.isLocalPath(cachedUrl)){
						this.saveVideo(cachedUrl)
					}else{
						// 下载视频文件
						uni.showLoading({
							title:'视频下载中...'
						})
						const downloadTask = uni.downloadFile({
							url: this.videoUrl,
							success: (downloadResult) => {
								if (downloadResult.statusCode === 200) {
									this.saveVideo(downloadResult.tempFilePath)
								} else {
									uni.showToast({
										title: '视频下载失败',
										icon: 'none'
									});
								}
								uni.hideLoading()
							},
							fail: (err) => {
								uni.showToast({
									title: '视频下载失败',
									icon: 'none'
								});
								uni.hideLoading()
							}
						});
						downloadTask.onProgressUpdate((res) => {
							console.log('下载进度' + res.progress);
							console.log('已经下载的数据长度' + res.totalBytesWritten);
							console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
						});
					}
				}
			},
			saveVideo(videoUrl){
				// 保存视频到相册
				const platform = uni.getSystemInfoSync().platform;
				if (platform === 'android' && (videoUrl.endsWith('.mov')|| videoUrl.endsWith('.MOV'))) {
				  uni.showToast({
				    title: '不支持的格式',
				    icon: 'none'
				  });
				  return
				}
				uni.saveVideoToPhotosAlbum({
					filePath: videoUrl,
					success: () => {
						uni.showToast({
							title: '视频保存成功',
							icon: 'none'
						});
					},
					fail: (err) => {
						console.log(err);
						uni.showToast({
							title: '视频保存失败',
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style scoped>
	video {
		position: relative;
	}
</style>